package music

import (
	"encoding/json"
	"fmt"
	"os"
	"strconv"

	//"strconv"
	//"fmt"
	"github.com/gin-gonic/gin"
	music2 "gomuisc/models/music"
	"gomuisc/service"
	"net/http"
	//"gomuisc/service/spider/sink"
	"gomuisc/models/mysql"
	"strings"
)

func GetList(c *gin.Context)  {
	keyword,ok := c.GetQuery("keyword");

	if !ok{
		c . JSON ( 200 , gin. H {
			"code":201,
			"msg" : "请输入查找内容" ,
		})
		return
	}


	songType := c.DefaultQuery("type","1000")
	PageNo := c.DefaultQuery("page","1")

	var url  ="https://music.163.com/weapi/cloudsearch/get/web?csrf_token="//请求列表
	//设置加密参数
	commentReqBody := music2.SeachParam{
		"<span class=\"s-fc7\">",
		"</span>",
		keyword,
		songType,
		PageNo,
		"true",
		"30",
		"",
	}

	resp,err :=service.HttpPostMuisc(url,commentReqBody);
	if err != nil {
		c . JSON ( http.StatusMovedPermanently , gin. H {
			"code":201,
			"msg" : "请求失败" ,
		})
		return
	}
	fmt.Println("测试 ----:", songType)
	switch songType {
		case "1":
			singles := handleSingle(resp)
			c . JSON ( http.StatusOK , gin.H{
				"code":200,
				"data":singles,
			})
			break
		case "100"://歌手搜索有问题
			//singers := handleSinger(resp)
			//c . JSON ( http.StatusOK , singers)
			break
		case "1000":
			sheets := handleSheet(resp)
			c . JSON ( http.StatusOK ,gin.H{
				"code":200,
				"data":sheets,
			})
			break
		default:
			c . JSON ( http.StatusMovedPermanently , gin. H {
				"code":201,
				"msg" : "类型错误" ,
			})
		break
	}
	return
}
func GetStoreList(c *gin.Context)  {
	fmt.Println("测试")
	keyword,ok := c.GetQuery("keyword");
	if !ok{
		//c . JSON ( 200 , gin. H {
		//	"msg" : "请输入查找内容" ,
		//})
		//return
	}
	fmt.Println("测试")
	songType := c.DefaultQuery("type","1")
	Page := c.DefaultQuery("page","0")
	PageNo,_ := strconv.Atoi(Page)
	mysqlSink,err := mysql.NewMysqlSink()
	if err != nil{
		return
	}
	defer mysqlSink.Close()
	switch songType {
		case "1":
			rows,ok :=mysqlSink.GetSingleList(PageNo,10,keyword)
			if ok !=nil{
				c . JSON ( 201 , gin. H {
					"code":201,
					"msg" : "异常" ,
				})
				return
			}
			c.JSON(http.StatusOK,gin.H{
				"code":200,
				"data":rows,
			})
			break;
		case "1000":
			rows,ok := mysqlSink.GetSheetList(0,10,keyword)
			if ok !=nil{
				c . JSON ( 201 , gin. H {
					"code":201,
					"msg" : "异常" ,
				})
				return
			}
			c.JSON(http.StatusOK,gin.H{
				"code":200,
				"data":rows,
			})
			break;
		default:
			break;
	}
	return
}
func SheetSearch(c *gin.Context)  {
	song_sheet_id,ok := c.GetQuery("song_sheet_id");
	if !ok{
		c . JSON ( 200 , gin. H {
			"code":201,
			"msg" : "请选择要查找的歌单" ,
		})
		return
	}
	//fmt.Println(song_sheet_id)
	var url = "https://music.163.com/playlist?id="+song_sheet_id
	singles := service.Http_get(url)
	c.JSON(http.StatusOK,gin.H{
		"code":200,
		"data":singles,
	})
	return
}
func GetSingerSingle(c *gin.Context)  {
	singer_id,ok := c.GetQuery("singer_id");
	if !ok{
		c . JSON ( 200 , gin. H {
			"code":301,
			"msg" : "请选择要查看的歌手" ,
		})
		return
	}
	singer_name,ok := c.GetQuery("singer_name");
	if !ok{
		c . JSON ( 200 , gin. H {
			"code":201,
			"msg" : "请选择要查看的歌手" ,
		})
		return
	}
	searchType := c.DefaultQuery("type","1")//搜索渠道 默认库内
	sid,err := strconv.Atoi(singer_id) //无法多重赋值
	if err != nil {
		fmt.Println(err)
		return
	}
	mysqlSink, err := mysql.NewMysqlSink()
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
	defer mysqlSink.Close()
	rows,err := mysqlSink.GetSingerRow(sid)
	if len(rows) == 0 {
		//没有该歌手	 这里可以改成自动获取名称
		mysqlSink.InsertSinger(mysql.Singer{
			Singer_id:sid,
			Name:singer_name,
		})
	}
	switch searchType {
		case "1":
			singles,err := mysqlSink.GetSingles(sid)
			if err != nil {
				fmt.Println(err)
				return
			}
			c.JSON(http.StatusOK, gin. H {
				"code":200,
				"data":singles,
			})
			break
		case "2":
			var url = "https://music.163.com/artist?id="+singer_id
			singles := service.Http_get(url)
			for key,_ := range singles{
				singles[key].Singer_id = sid //不能修改v的值
				singles[key].Singer = singer_name //不能修改v的值
			}
			for _,v := range singles{
				has,_ := mysqlSink.GetSingle(v.Song_id)
				if has == false{
					_,err := mysqlSink.InsertSingle(v)
					if err != nil {
						fmt.Println(err)
						break
					}
				}
			}
			c.JSON(http.StatusOK, gin. H {
				"code":200,
				"data":singles,
			})
			break;
		default:
			c . JSON ( 200 , gin. H {
				"code":201,
				"msg" : "暂不支持" ,
			})
			break
	}
	//先查看库内有没有

	//可能存在没有主页的情况 所以不获取更具体的资料了
	//if rows[0].Fans == ""{
	//	 GetSingerRow(sid)
	//	fmt.Println("数据是",rows[0].Fans)
	//}else{
	//	row  := rows[0]
	//}
	//fmt.Println(row)

	return
}
func GetSingerInfo(c *gin.Context)  {
	singer_id,ok := c.GetQuery("singer_id");
	if !ok{
		c . JSON ( 200 , gin. H {
			"code":201,
			"msg" : "请选择要查看的歌手" ,
		})
		return
	}
	sid,err := strconv.Atoi(singer_id) //无法多重赋值
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
	mysqlSink, err := mysql.NewMysqlSink()
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
	defer mysqlSink.Close()
	//先查看库内有没有
	rows,err := mysqlSink.GetSingerRow(sid)
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
	fmt.Println(rows)
	//可能存在没有主页的情况 所以不获取更具体的资料了
	//if rows[0].Fans == ""{
	//	 GetSingerRow(sid)
	//	fmt.Println("数据是",rows[0].Fans)
	//}else{
	//	row  := rows[0]
	//}
	//fmt.Println(row)


}
func GetSheet(c *gin.Context)  {
	mysqlSink,err := mysql.NewMysqlSink()
	if err != nil{
		return
	}
	defer mysqlSink.Close()

	user_id,_ :=c.Get("user_id")
	rows,err := mysqlSink.GetSheets(user_id.(int))
	if err !=nil{
		c . JSON ( 200 , gin. H {
			"code":301,
			"msg" : "异常" ,
		})
		return
	}
	c . JSON ( 200 , gin. H {
		"code":200,
		"msg" : "" ,
		"data":rows,
	})
	return
}
func AddSheet(c *gin.Context)  {
	song_id,ok := c.GetPostForm("song_id");
	fmt.Println(song_id)
	if !ok{
		c . JSON ( 200 , gin. H {
			"code":301,
			"msg" : "没有歌曲ID" ,
		})
		return
	}
	song_name,ok := c.GetPostForm("song_name");
	if !ok{
		c . JSON ( 200 , gin. H {
			"code":201,
			"msg" : "没有歌曲名称" ,
		})
		return
	}


	fmt.Println(song_name)
	song_name = strings.TrimSpace(song_name)
	fmt.Println("新字符串",song_name)
	sid,err := strconv.Atoi(song_id)
	mysqlSink,err := mysql.NewMysqlSink()
	if err != nil{
		return
	}
	defer mysqlSink.Close()

	user_id,_ :=c.Get("user_id")


	has,err := mysqlSink.GetUsheet(sid,user_id.(int))
	if err != nil{
		c . JSON ( 200 , gin. H {
			"code":201,
			"msg" : "添加失败" ,
		})
		return
	}

	fmt.Println(has)

	if has == true{
		c . JSON ( 200 , gin. H {
			"code":201,
			"msg" : "该歌曲已经在歌单" ,
		})
		return
	}


	_,err = mysqlSink.InsUsheet(mysql.UserSheet{
		Song_id: sid,
		User_id: user_id.(int),
		Song_name: song_name,
	})
	if err != nil{
		c . JSON ( 200 , gin. H {
			"code":201,
			"msg" : "添加失败" ,
		})
		return
	}
	c . JSON ( 200 , gin. H {
		"code":200,
		"msg" : "添加成功" ,
	})
	return
	//fmt.Println(res)
	//fmt.Println(ok)

}





func handleSingle(resp []byte) (singles []mysql.Single) {
	typeSong := music2.Single{}
	json.Unmarshal(resp, &typeSong)
	mysqlSink, err := mysql.NewMysqlSink()
	if err != nil {
		fmt.Println(err)
		return
	}
	defer mysqlSink.Close()

	//保存
	singles = make([]mysql.Single, 0, len(typeSong.SingleResult.Songs))
	singers := make([]mysql.Singer, 0, len(typeSong.SingleResult.Songs))
	for _, v := range typeSong.SingleResult.Songs{
			single := mysql.Single{
				Song_id: v.ID,
				Song_name :v.Name,
				Singer  :v.Ar[0].Name,
				Album  :v.Al.Name,
				Duration :v.Dt,
				//Createtime int `json:"createtime"xorm:"created"`
				Sheet_id  :v.Al.ID,
				Singer_id  :v.Ar[0].ID,
			}
			if v.Ar[0].ID != 0{
				singer := mysql.Singer{
					Singer_id:v.Ar[0].ID,
					Name:v.Ar[0].Name,
				}
				singers = append(singers, singer)
			}

			singles = append(singles, single)
	}
	for _,v := range singers{
		has,_ := mysqlSink.GetSinger(v.Singer_id)
		if has == false{
			_,err := mysqlSink.InsertSinger(v)
			if err != nil {
				fmt.Println(err)
				break
			}
		}
	}
	for _,v := range singles{
		has,_ := mysqlSink.GetSingle(v.Song_id)
		if has == false{
			_,err := mysqlSink.InsertSingle(v)
			if err != nil {
				fmt.Println(err)
				break
			}
		}
	}
	return singles
}
func handleSinger(resp []byte)  {
	typeSong := music2.Singer{}
	json.Unmarshal(resp, &typeSong)

}
func getSingerSingles(sid int)  {

}
func handleSheet(resp []byte)(sheets []mysql.SongSheet)  {
	typeSong := music2.SongSheetList{}
	json.Unmarshal(resp, &typeSong)
	mysqlSink, err := mysql.NewMysqlSink()
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
	defer mysqlSink.Close()
	//保存
	sheets = make([]mysql.SongSheet, 0, len(typeSong.Result.Playlists))
	for _, v := range typeSong.Result.Playlists{
		sheet := mysql.SongSheet{
			Song_sheet_id:v.ID,
			Sheet_name :v.Name,
			TrackCount :v.TrackCount,
		}

		sheets = append(sheets, sheet)
	}
	for _,v := range sheets{
		res,_ := mysqlSink.GetSheet(v.Song_sheet_id)
		if res == false{
			err := mysqlSink.InsertSheet(v)
			if err != nil {
				fmt.Println(err)
				break
			}
		}
	}
	return sheets
}
func GetComment(c *gin.Context)(){
	SongId,ok := c.GetQuery("songId");
	if !ok{
		c . JSON ( 200 , gin. H {
			"code":201,
			"msg" : "请输入歌曲ID" ,
		})
		return
	}
	var PageNo = "1";
	var url  ="https://music.163.com/weapi/comment/resource/comments/get?csrf_token="//请求地址不变改变 只改变歌曲ID
	commentReqBody := music2.CommentRequestBody{
		Rid: "R_SO_4_" + SongId,
		ThreadId: "R_SO_4_" + SongId,
		PageNo:    PageNo,
		Offset:    "0",
		OrderType:"1",
		Cursor:"-1",
		PageSize:     "20",
		CsrfToken: "",
	}
	result,err := service.HttpPostMuisc(url,commentReqBody)
	if err != nil {
		return
	}
	var json1 music2.AutoGenerated
	json.Unmarshal([]byte(string(result)), &json1)
	c.JSON(http.StatusOK,gin.H{
		"code":200,
		"data":json1,
	})
	return
}

